<template>
  <el-upload
    class="avatar-uploader"
    action="string"
    :before-upload="canAddPhoto"
    :show-file-list="false"
    :http-request="Upload"
  >
    <img v-if="objectA" :src="objectA" class="avatar" >
    <i v-else class="el-icon-plus avatar-uploader-icon" />
    <div style="display:none;">{{ photolist }}</div>
  </el-upload>
</template>

<script>
import OSS from 'ali-oss';
const client = new OSS({
  region: 'oss-cn-shanghai',
  accessKeyId: 'LTAIxZYjNPM6pgO3',
  accessKeySecret: '11iG8LcwySD1Ryw8aT1PVrQitMNYUl',
  bucket: 'syg-photo'
})
export default {
  props: ['list', 'dataId', 'typeCode', 'remark'],
  data() {
    return {
      objectA: this.photolist
    }
  },
  computed: {
    photolist() {
      if (this.$props.list.length) {
        this.objectA = this.$props.list[0].fileUrl
        return this.$props.list[0].fileUrl
      } else {
        this.objectA = '';
        return '';
      }
    }
  },
  methods: {
    canAddPhoto(res) {
      if (!res.type.includes('image')) {
        this.$message.error('只能上传图片文件')
        return false
      }
    },
    Upload(file) {
      const that = this
      if(file.file.size / 1024 > 500){
        this.$message.error('请上传不大于500KB的图片文件')
        return false
      }
      let javaSize = parseInt(file.file.size / 1024)
      let javaDateType = '.' + file.file.type.split('/')[1]
      let fileName = file.file.name
      let sourceFileName = 'photo-' + fileName + '-' + Date.parse(new Date())
      let uid = file.file.uid
      client.put(sourceFileName, file.file).then(res => {
        const newImageInfo = {
          dataId: that.dataId,
          dataType: that.remark,
          extName: javaDateType,
          fileName: fileName,
          fileType: 0,
          fileUrl: res.url,
          id: this.$props.list.length ? this.$props.list[0].id : 'string',
          ident: this.$props.list.length ? 2 : 1,
          size: javaSize,
          sort: 0,
          sourceFileName: sourceFileName,
          typeCode: that.typeCode,
          uid: uid
        }
        this.objectA = res.url
        that.$emit('changeadvert', newImageInfo)
      })
    }
  }
}
</script>

<style >
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
